package ua.eug.airv1.weapon;

import ua.eug.airv1.controllers.ScreenController;
import ua.eug.airv1.map.IOnScreen;
import ua.eug.airv1.map.Tile;
import ua.eug.airv1.map.TilePos;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;

public class ExplosionPool extends Group implements IOnScreen {

	private final Array<Explosion> activeExplosions = new Array<Explosion>(false,4);
	private final Pool<Explosion> explosions = new Pool<Explosion>() {
        @Override
        protected Explosion newObject() {
            return new Explosion();
        }
	};

	protected ExplosionPool() {
		super();
		ScreenController.getInstance().addSlave(this);
	}
	
	public static class SingletonHolder {
        public static final ExplosionPool HOLDER = new ExplosionPool();
    }
	
	public static ExplosionPool getInstance() {
        return SingletonHolder.HOLDER;
    }

	@Override
	public void pan(float x, float y) {
		this.setPosition(x, y);
	}

	@Override
	public void zoom(float z) {
		this.setScale(z);
	}


	public void newExplosion(Tile t) {
		Explosion ex = explosions.obtain();
		ex.tile = t;
		TilePos pos = t.pos;
		Vector2 p = ScreenController.getInstance().XyToStage(pos.x,pos.y);
		ex.setPosition(p.x, p.y);
		ex.init();
		activeExplosions.add(ex);
		this.addActor(ex);
		Gdx.input.vibrate(200);
	}
	
	public void removeExplosion(Explosion ex) {
		ex.tile.setExplode(false);
		ex.tile = Tile.ZTile;
		activeExplosions.removeValue(ex, false);
		explosions.free(ex);
	}
	
	public Boolean isOnScreen() {
		return (activeExplosions.size > 0);
	}
	
	@Override
	public void act(float sec) {
		for (Explosion ex: activeExplosions) {
			ex.act(sec);
		}
	}
}
